<template>
  <div>
    <!-- card背景 -->
    <el-card class="box-card">
      <!-- 功能按钮 -->
      <el-row :gutter="10">
        <el-col :span="2.5">
          <el-button type="primary" @click="invoke()" size="medium" class="edit"  icon="el-icon-check">
            保存API
          </el-button>
        </el-col>
      </el-row>

      <!-- 接口请求表单区域 -->
      <el-form
        :model="invokeHttpForm"
        :rules="rules"
        ref="invokeHttpRef"
        size="small"
        label-position="right"
      >
        <el-row :gutter="25">
          <!-- 域名 -->
          <el-col :span="7">
            <el-form-item label="API名称：" prop="apiName" label-width="90px">
              <el-input v-model="invokeHttpForm.apiName"></el-input>
            </el-form-item>
          </el-col>
          <el-col span="5">
            <el-form-item label="请求类型：" prop="method" label-width="100px">
              <el-select
                v-model="invokeHttpForm.type"
                placeholder="请选择"
                @change="resetInput()"
              >
                <el-option
                  v-for="item in typesOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="项目选择：" prop="projectsName" label-width="100px">
              <el-select
                v-model="invokeHttpForm.projectsName"
                placeholder="请选择"
                @change="getDept()"
              >
                <el-option
                  v-for="item in projectsOptions"
                  :key="item.projectsName"
                  :label="item.projectsName"
                  :value="item.projectsName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="25">
          <!-- 域名 -->
          <el-col :span="7">
            <el-form-item label="域名：" prop="host" label-width="90px">
              <el-input v-model="invokeHttpForm.host"></el-input>
            </el-form-item>
          </el-col>
          <!-- 接口地址 -->
          <el-col :span="10">
            <el-form-item label="接口地址：" prop="apiurl" label-width="100px">
              <el-input v-model="invokeHttpForm.apiurl"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="25">
          <!-- 超时时间下拉选择 -->
          <el-col :span="5">
            <el-form-item
              label="超时时间(s):"
              prop="timeOut"
              label-width="100px"
            >
              <el-select v-model="invokeHttpForm.timeout" placeholder="请选择">
                <el-option
                  v-for="item in timeOutOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 请求方法下拉选择-->
          <el-col :span="5">
            <el-form-item label="请求方法：" prop="method" label-width="100px">
              <el-select
                v-model="invokeHttpForm.method"
                placeholder="请选择"
                @change="resetInput()"
              >
                <el-option
                  v-for="item in methodsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 添加请求参数开关 -->
          <el-col :span="2">
            <el-form-item
              label="请求参数："
              prop="param"
              label-width="110px"
            >
              <el-switch
                v-model="isParams"
                @change="activeChange('param')"
              ></el-switch>
            </el-form-item>
          </el-col>
          <!-- 添加请求体开关 -->
          <el-col :span="2">
            <el-form-item
              label="请求体："
              prop="body"
              label-width="140px">
              <el-switch
                v-model="isBody"
                @change="activeChange('body')"
              ></el-switch>
            </el-form-item>
          </el-col>
          <!-- 添加信息头开关 -->
          <el-col :span="2.5">
            <el-form-item
              label="预计响应结果："
              prop="header"
              label-width="240px"
            >
              <el-switch
                v-model="isExample"
                @change="activeChange('example')"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 信息头/入参表单 -->
      <el-form :model="reqForm" ref="reqRef" size="small">
        <el-tabs v-if="isHeader || isParams || isBody || isExample" v-model="activeName">

          <!-- 请求参数表单 -->
          <el-tab-pane v-if="isParams" label="请求参数" name="param">
            <el-row :gutter="22" class="title">
              <el-col :span="9">
                <span>参数:</span>
              </el-col>
              <el-col :span="9">
                <span>参数说明:</span>
              </el-col>
            </el-row>
            <el-form-item
              v-for="(param, index) in reqForm.requestParams"
              :key="index"
              :prop="'params.' + index + '.value'"
            >
              <el-row :gutter="22">
                <el-col :span="9">
                  <el-input v-model="param.key"></el-input>
                </el-col>
                <el-col :span="9">
                  <el-input v-model="param.value"></el-input>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="success"
                    icon="el-icon-plus"
                    size="mini"
                    @click="add('param')"
                  ></el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    v-if="index > 0"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click.prevent="removeDomain(param, 'param')"
                  ></el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane v-if="isBody" label="请求体" name="body">
            <div style="width: 70%;margin-left: 30px;margin-top: 30px;">
              <b-code-editor v-model="invokeHttpForm.requestBody" :auto-format="true" :smart-indent="true"  :indent-unit="4" :line-wrap="false" ref="editor"></b-code-editor>
              <br>
            </div>
          </el-tab-pane>
          <el-tab-pane v-if="isExample" label="返回示例" name="example">
            <div style="width: 70%;margin-left: 30px;margin-top: 30px;">
                <b-code-editor v-model="invokeHttpForm.returnExample" :auto-format="true" :smart-indent="true"  :indent-unit="4" :line-wrap="false" ref="editor"></b-code-editor>
              <br>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>


    </el-card>
  </div>
</template>

<script>
import {invoke, save} from "../../../../src/api/APIFile/testhttp";
import 'vue-json-pretty/lib/styles.css';
import {allProject} from "@/api/system/project";
import {addApi} from "@/api/system/api";
const jsonData =`{
  }`
export default {
  mounted(){
    this.getDept();
  },
  data() {
    return {
      jsonStr:jsonData,
      invokeHttpRules: {},
      // 响应对象
      response: {
        headers: {},
        body: {},
        statutCode: ""
      },
      // 接口请求时提交的表单对象
      invokeHttpForm: {
        apiName:"",
        host: "localhost:8082",
        apiurl: "/test/delete",
        timeout: "3000",
        method: "get",
        headers: "",
        type: "http",
        requestParams: "",
        requestBody: "{}",
        returnExample:"{}",
        projectsName:""
      },
      // 下拉列表选项
      timeOutOptions: [
        {
          value: "1000",
          label: "1秒"
        },
        {
          value: "2000",
          label: "2秒"
        },
        {
          value: "3000",
          label: "3秒"
        },
        {
          value: "4000",
          label: "4秒"
        },
        {
          value: "5000",
          label: "5秒"
        }
      ],
      methodsOptions: [
        {
        value: "get",
        label: "GET"
        },
        {
          value: "post",
          label: "POST"
        },
        {
          value: "put",
          label: "PUT"
        },
        {
          value: "delete",
          label: "DELETE"
        }],
      typesOptions: [
        {
          value: "http",
          label: "HTTP"
        },
        {
          value: "https",
          label: "HTTPS"
        }
      ],
      projectsOptions:[],
      // 判断入参和头部开关是否开启
      isHeader: false,
      isParams: false,
      isBody: false,
      isExample:false,
      // 默认tab激活状态的标签
      activeName: "",
      activeNameRes: "responseResult",
      // 请求表单对应的请求对象数组
      reqForm: {
        headers: [{ key: "", value: "" }],
        requestParams: [{ key: "", value: "" }],
        requestBody: "",
        example:""
      },
      rules: {
        apiName: [
          { required: true, message: "API接口名称不能为空", trigger: "blur" }
        ],
        projectsName: [
          { required: true, message: "所属项目名称不能为空", trigger: "blur" }
        ],
        method: [
          { required: true, message: "请求方式不能为空", trigger: "blur" }
        ],
        host: [
          { required: true, message: "api的host不能为空", trigger: "blur" }
        ],
        apiurl: [
          { required: true, message: "api的地址不能为空", trigger: "blur" }
        ],
        timeout: [
          { required: true, message: "超时时间不能为空", trigger: "blur" }
        ],
        requestParams: [
          { required: true, message: "请求参数不能为空", trigger: "blur" }
        ],
        requestBody: [
          { required: true, message: "请求示例不能为空", trigger: "blur" }
        ],
        returnExample: [
          { required: true, message: "返回示例不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },

  methods: {
    getDept()
    {
      allProject().then((response) => {
        this.projectsOptions = response.rows;
        console.log(this.projectsOptions);
        console.log(response.rows);
      });
    },

    // 调用测试接口
    invoke() {
      if (this.invokeHttpForm.methods===""
        || this.invokeHttpForm.host===""
        || this.invokeHttpForm.apiName===""
        || this.invokeHttpForm.apiurl===""
        || this.invokeHttpForm.projectsName==="" ){
        window.alert("请填写全部信息.")
      }else {
        console.log("保存接口");
        // 如果前端有输入，存入对象数组，则将对象数组存入一个对象并转为string
        if (this.reqForm.headers[0].key !== "") {
          let headersObj = {};
          for (let i = 0; i < this.reqForm.headers.length; i++) {
            let key = this.reqForm.headers[i].key;
            let val = this.reqForm.headers[i].value;
            headersObj[key] = val;
          }
          this.invokeHttpForm.headers = JSON.stringify(headersObj);
        }
        // 如果前端有输入，存入对象数组，则将对象数组存入一个对象并转为string
        console.log("表单数据显示：", JSON.stringify(this.reqForm.requestParams));
        console.log("json：", this.reqForm.body);
        if (this.reqForm.requestParams[0].key !== "") {
          let paramsObj = {};
          for (let i = 0; i < this.reqForm.requestParams.length; i++) {
            var key = this.reqForm.requestParams[i].key;
            var val = this.reqForm.requestParams[i].value;
            paramsObj[key] = val;
            console.log("遍历表单数据key：", this.reqForm.requestParams[i].key);
          }
          console.log("表单对象数组转对象后显示：：", JSON.stringify(paramsObj));
          if (this.invokeHttpForm.method.includes("post")) {
            this.invokeHttpForm.requestParams = JSON.stringify(paramsObj);
            this.invokeHttpForm.body = this.reqForm.body;
          } else if (this.invokeHttpForm.method.includes("get")) {
            this.invokeHttpForm.requestParams = JSON.stringify(paramsObj);
          }
          console.log("对象转请求字符串后显示：", this.invokeHttpForm.requestParams);
        }
        console.log("数据！！！！！",this.invokeHttpForm);
        try {
          JSON.parse(this.invokeHttpForm.returnExample);
          JSON.parse(this.invokeHttpForm.requestBody);
          addApi(this.invokeHttpForm).then(
            res => {
            });
        } catch (e) {
          console.log(e);
          window.alert("Json格式错误，访问被拒绝")
          return false;
        }
        window.alert("API接口保存成功")
      }
    },
    activeChange(activeName) {
      if (activeName.includes("header") && this.isHeader) {
        console.log("header1");
        this.activeName = "header";
      } else if (activeName.includes("header")) {
        console.log("param2");
        this.activeName = "param";
      }
      if (activeName.includes("param") && this.isParams) {
        console.log("param1");
        this.activeName = "param";
      } else if (activeName.includes("param")) {
        console.log("header2");
        this.activeName = "header";
      }
      if (activeName.includes("body") && this.isBody) {
        console.log("body1");
        this.activeName = "body";
      } else if (activeName.includes("body")) {
        console.log("body2");
        this.activeName = "body";
      }
      if (activeName.includes("example") && this.isExample) {
        console.log("example1");
        this.activeName = "example";
      } else if (activeName.includes("example")) {
        console.log("example2");
        this.activeName = "example";
      }
    },
    // 添加消息头
    add(tab) {
      if (tab.includes("header")) {
        this.reqForm.headers.push({
          value: "",
          key: ""
        });
      } else if (tab.includes("param")) {
        this.reqForm.requestParams.push({
          value: "",
          key: ""
        });
      }
    },
    // 删除消息头
    removeDomain(item, tab) {
      if (tab.includes("header")) {
        let index = this.reqForm.headers.indexOf(item);
        if (index !== -1) {
          this.reqForm.headers.splice(index, 1);
        }
      } else if (tab.includes("param")) {
        let index = this.reqForm.requestParams.indexOf(item);
        if (index !== -1) {
          this.reqForm.requestParams.splice(index, 1);
        }
      }
    }
    },
    // 检测json格式
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj=JSON.parse(str);
          if(typeof obj == 'object' && obj ){
            return true;
          }else{
            return false;
          }

        } catch(e) {
          return false;
        }
      }else if (typeof str == 'object'  && str) {
        return true;
      }
    }
};
</script>

<style lang="less" scoped>
.el-col {
  border-radius: 4px;
}
.el-button {
  margin-bottom: 20px;
}
.title {
  margin-bottom: 10px;
}
.edit {
  color: #fff;
  background-color: rgb(255, 0, 0);
  border-color: rgb(255, 0, 0);
}
.edit:hover,
.edit:focus {
  background: var(--el-button-hover-color);
  border-color: var(--el-button-hover-color);
  color: var(--el-button-font-color);
}
.edit1 {
  color: #fff;
  background-color: rgb(30, 130, 229);
  border-color: rgb(30, 130, 229);
}
.edit1:hover,
.edit1:focus {
  background: var(--el-button-hover-color);
  border-color: var(--el-button-hover-color);
  color: var(--el-button-font-color);
}
</style>

